package org.metcat.core.metadata;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

/**
 * Author: Bhathiya Jayasekara
 * Date: 11/04/12
 * Time: 11:47 AM
 */

public class MetadataExtractor {
	XPathFactory xpathFactory;
	XPath xpath;
	
	public MetadataExtractor() {
		xpathFactory = XPathFactory.newInstance();
		xpath = xpathFactory.newXPath();
	    String prefix = "wor";
	    String uri = "http://lead.extreme.indiana.edu/namespaces/2006/06/workflow_tracking";
	    xpath.setNamespaceContext(new NamespaceContextMapper(prefix, uri));
	}
	
	public static void main(String[] args){
		InputSource message = new InputSource("test.xml");  		
		MetadataExtractor ext = new MetadataExtractor();
		ext.extractMetadata(message);
	}
	
	public void extractMetadata(InputSource message){
		String eventMessageType = getEventMessageType(message);
		System.out.println(eventMessageType);
		String workflowId = getWorkflowId(message);
		System.out.println(workflowId);
	}
	
	private String getWorkflowId(InputSource message){
  		XPathExpression expr = null;
		String id = null;
		try {
			expr = xpath.compile("//wor:notificationSource/@wor:workflowID");
			id = expr.evaluate(message);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return id;
	}
	
	private String getEventMessageType(InputSource message){
		XPathExpression expr = null;
		String type = null;
		try {
			expr = xpath.compile("local-name(*)");
			type = (String) expr.evaluate(message);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return type;
	}
}
